package data_operater

import "fmt"

type StateMove interface {
	GetSourceState() State
	GetTargetState() State
	IsMatch(char string) bool
}

// NewStateMoveManager 状态转移管理器
func NewStateMoveManager(stateMoves ...StateMove) *StateMoveManager {
	stateMover := StateMoveManager{stateMoveMap: make(map[State][]StateMove)}
	if len(stateMoves) > 0 {
		for _, sm := range stateMoves {
			stateMover.AddStateMove(sm)
		}
	}
	return &stateMover
}

type StateMoveManager struct {
	stateMoveMap map[State][]StateMove
}

func (s *StateMoveManager) AddStateMove(sm StateMove) {
	if moves, ok := s.stateMoveMap[sm.GetSourceState()]; ok {
		for _, move := range moves {
			if move.GetTargetState() == sm.GetTargetState() {
				panic(fmt.Sprintf("状态转移类重复注册：%d->%d", sm.GetSourceState(), sm.GetTargetState()))
			}
		}
		s.stateMoveMap[sm.GetSourceState()] = append(s.stateMoveMap[sm.GetSourceState()], sm)
	} else {
		s.stateMoveMap[sm.GetSourceState()] = []StateMove{
			sm,
		}
	}
}

func (s *StateMoveManager) MoveTo(sourceState State, char string) (State, error) {
	if movers, ok := s.stateMoveMap[sourceState]; ok {
		for _, move := range movers {
			if move.IsMatch(char) {
				return move.GetTargetState(), nil
			}
		}
		return 0, fmt.Errorf("解析错误：没有匹配的状态转移方程：%d", sourceState)
	}
	return 0, fmt.Errorf("解析错误：不支持的状态：%d", sourceState)
}
